package cn.emall.content.service.impl;

import cn.emall.content.service.ContentCatService;
import cn.emall.mapper.TbContentCategoryMapper;
import cn.emall.mapper.TbItemCatMapper;
import cn.emall.pojo.*;
import cn.emall.utils.EmallResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 内容分类管理Service
 */
@Service
public class ContentCatServiceImpl implements ContentCatService{

    @Autowired
    private TbContentCategoryMapper tbContentCategoryMapper;

    @Override
    public List<EasyUITreeNode> getTreeNode(Long parentId) {
        // 根据parentid查询子节点列表
        TbContentCategoryExample example = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        //设置查询条件
        criteria.andParentIdEqualTo(parentId);
        //执行查询
        List<TbContentCategory> lists = tbContentCategoryMapper.selectByExample(example);
        //转换成EasyUITreeNode的列表
        List<EasyUITreeNode> treeNodes = new ArrayList<>();
        for (TbContentCategory tb: lists) {
            EasyUITreeNode node = new EasyUITreeNode();
            node.setId(tb.getId());
            node.setText(tb.getName());
            node.setState(tb.getIsParent()?"closed":"open");
            //添加到列表
            treeNodes.add(node);
        }
        return treeNodes;
    }

    @Override
    public EmallResult addTree(Long parentId, String name) {
        TbContentCategory tbContentCategory = new TbContentCategory();
        tbContentCategory.setParentId(parentId);
        tbContentCategory.setName(name);
        //新添加的节点一定是叶子节点
        tbContentCategory.setIsParent(false);
        tbContentCategory.setCreated(new Date());
        tbContentCategory.setUpdated(new Date());
        //1(正常),2(删除)
        tbContentCategory.setStatus(1);
        //默认排序就是1
        tbContentCategory.setSortOrder(1);
        tbContentCategoryMapper.insert(tbContentCategory);
        //判断父节点的isparent属性。如果不是true改为true
        //根据parentid查询父节点
        TbContentCategory parent = tbContentCategoryMapper.selectByPrimaryKey(parentId);
        if(!parent.getIsParent()){
            parent.setIsParent(true);
            //更新到数数据库
            tbContentCategoryMapper.updateByPrimaryKey(parent);
        }
        //返回结果，返回E3Result，包含pojo
        return EmallResult.ok(tbContentCategory);
    }
}
